package com.example.ktapplication.dialog

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentResolver
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.ktapplication.adapter.MessageAdapter
import com.example.ktapplication.bean.MessageBean
import com.example.ktapplication.databinding.DialogBottomSheetBinding
import com.example.ktapplication.utils.ToastUtil
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
class BottomSheetDialog(activity: Activity) : BottomSheetDialogFragment() {

    private lateinit var binding: DialogBottomSheetBinding

    ///相册
    private val REQUEST_CONTACTS_PERMISSION_CODE: Int = 107
    ///电话
    private val REQUEST_PHONE_PERMISSION_CODE: Int = 102

    val READ_CONTACTS_PMSN = Manifest.permission.READ_CONTACTS
    val GRANTED = PackageManager.PERMISSION_GRANTED

    var number: String="114"

    val messageData by lazy {
        mutableListOf<MessageBean>()
    }

    private lateinit var context:Activity
    val contentResolver: ContentResolver by lazy {
        context.contentResolver
    }

    private val messageAdapter by lazy {
        MessageAdapter().apply {
            itemCallBack = object : MessageAdapter.OnItemClickListener{
                override fun onItemClick(bean: MessageBean) {
                    number=bean.number
                    val perArray = arrayOf(Manifest.permission.CALL_PHONE)
                    requestPerssiom(perArray,REQUEST_PHONE_PERMISSION_CODE,object : Callback {
                        override fun onComplete(result: Int) {
                            if (result==REQUEST_PHONE_PERMISSION_CODE){
                                // 权限已经授予，可以直接使用电话
                                startCallPhone(bean.number)
                            }
                        }
                        override fun onFail() {
                            ToastUtil.showToast(context,"没有电话呼叫权限")
                        }
                    })
                }
            }
            addData(messageData)
        }
    }

    init {
        this.context=activity
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?): View? {
        binding = DialogBottomSheetBinding.inflate(layoutInflater)
        if (messageData.size<=0){
            binding.llEmptyData.visibility=View.VISIBLE
            binding.rvMessage.visibility=View.GONE
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val perArray = arrayOf(READ_CONTACTS_PMSN)
        requestPerssiom(perArray,REQUEST_CONTACTS_PERMISSION_CODE,object : Callback {
            override fun onComplete(result: Int) {
                if (result==REQUEST_CONTACTS_PERMISSION_CODE){
                    readContact()
                }
            }
            override fun onFail() {
                ///没有权限
                binding.rvMessage.apply {
                    layoutManager = LinearLayoutManager(context)
                    adapter = messageAdapter
                }
                if (messageData.size<=0){
                    binding.llEmptyData.visibility=View.VISIBLE
                    binding.rvMessage.visibility=View.GONE
                }else{
                    binding.llEmptyData.visibility=View.GONE
                    binding.rvMessage.visibility=View.VISIBLE
                }
            }
        })
    }

    override fun onRequestPermissionsResult(requestCode: Int,
                                            permissions: Array<out String>,
        grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CONTACTS_PERMISSION_CODE) {
            if (grantResults.size > 0 && grantResults[0] == GRANTED) {
                // 权限被授予
                ToastUtil.showToast(context,"获取到通信录使用权限")
                readContact()
            } else {
                // 权限被拒绝，处理这种情况，例如提示用户手动开启权限或功能不可用等。
                ToastUtil.showToast(context,"通信录使用权限被拒绝")
                binding.rvMessage.apply {
                    layoutManager = LinearLayoutManager(context)
                    adapter = messageAdapter
                }
                if (messageData.size<=0){
                    binding.llEmptyData.visibility=View.VISIBLE
                    binding.rvMessage.visibility=View.GONE
                }else{
                    binding.llEmptyData.visibility=View.GONE
                    binding.rvMessage.visibility=View.VISIBLE
                }
            }
        }
        if (requestCode == REQUEST_PHONE_PERMISSION_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，使用摄像头功能
                ToastUtil.showToast(context,"获取到电话使用权限")
                startCallPhone(number)
            } else {
                // 权限被拒绝，处理这种情况，例如提示用户手动开启权限或功能不可用等。
                ToastUtil.showToast(context,"没有电话呼叫权限")
            }
        }
    }
    // 读取联系人数据
    @SuppressLint("Range")
    fun readContact() {
        val uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        val nameColStr = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
        val numberColStr = ContactsContract.CommonDataKinds.Phone.NUMBER
        contentResolver.query(uri, null, null, null, null)
            ?.apply {
                while (moveToNext()) {
                    val name = getString(getColumnIndex(nameColStr))
                    val number = getString(getColumnIndex(numberColStr))
                    val messageBean= MessageBean(name,number)
                    messageData.add(messageBean)
                }
                close()
            }
        binding.rvMessage.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = messageAdapter
        }
        if (messageData.size<=0){
            binding.llEmptyData.visibility=View.VISIBLE
            binding.rvMessage.visibility=View.GONE
        }else{
            binding.llEmptyData.visibility=View.GONE
            binding.rvMessage.visibility=View.VISIBLE
        }
    }

    private fun requestPerssiom(permissions:Array<String>,requestCode:Int,callback: Callback){
        if (ContextCompat.checkSelfPermission(context,
                permissions[0]) != GRANTED) {
            ActivityCompat.requestPermissions(context, permissions,
                requestCode);
        } else {
            // 权限已经授予
            callback.onComplete(requestCode)
        }
    }

    private fun startCallPhone(number:String) {
        val callIntent = Intent(Intent.ACTION_CALL)
        callIntent.setData(Uri.parse("tel:$number"))
        startActivity(callIntent)
    }

    interface Callback {
        fun onComplete(result: Int)
        fun onFail()
    }


    override fun onDestroy() {
        super.onDestroy()
    }
}